import { type AnyFieldApi, useForm } from "@tanstack/react-form";
import { Navigate, useNavigate } from "react-router";
import { z } from "zod";
import Button from "@/components/Button";
import Input from "@/components/Input";
import Panel from "@/components/Panel";
import useAuthStore from "@/store/auth";

export default function LoginPage() {
  const auth = useAuthStore((state) => state);
  const navigate = useNavigate();

  const form = useForm({
    defaultValues: {
      username: "",
      password: "",
    },
    validators: {
      onChange: z.object({
        username: z.string().min(3, "用户名至少应包含3个字符。"),
        password: z.string().min(6, "密码至少应包含6个字符。"),
      }),
    },
    onSubmit: async ({ value }) => {
      const result = await auth.login(value.username, value.password);
      if (result.ok) {
        navigate("/");
      } else {
        alert(result.message);
      }
    },
  });

  if (auth.status === "ok") {
    return <Navigate to="/" />;
  }

  return (
    <Panel className="w-80 mt-12 mx-auto">
      <form
        className="flex flex-col gap-4"
        onSubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <h1>登录</h1>
        <form.Field name="username">
          {(field) => (
            <>
              <label htmlFor="username">用户名：</label>
              <Input
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
              />
              <FieldInfo field={field} />
            </>
          )}
        </form.Field>
        {/* The "name" property will throw a TypeScript error if typo'd  */}
        <form.Field name="password">
          {(field) => (
            <>
              <label htmlFor="password">密码：</label>
              <Input
                type="password"
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
              />
              <FieldInfo field={field} />
            </>
          )}
        </form.Field>
        <form.Subscribe selector={(state) => [state.canSubmit, state.isSubmitting]}>
          {([canSubmit, isSubmitting]) => (
            <Button type="submit" disabled={!canSubmit}>
              {isSubmitting ? "..." : "登录"}
            </Button>
          )}
        </form.Subscribe>
      </form>
    </Panel>
  );
}

function FieldInfo({ field }: { field: AnyFieldApi }) {
  return (
    <>
      {field.state.meta.isTouched && field.state.meta.errors.length ? (
        <em>{field.state.meta.errors[0].message}</em>
      ) : null}
      {field.state.meta.isValidating ? "Validating..." : null}
    </>
  );
}
